#!/usr/bin/python
#coding:utf8
'''
Proxy
'''
# 场景1 授权机制
from abc import ABC, abstractmethod
class Server(ABC):
    @abstractmethod
    def recv(self,info):
        pass
    @abstractmethod
    def send(self,info):
        pass
    @abstractmethod
    def show(self,info):
        pass

class InfoServer(Server):
    def recv(self,info):
        self.content = info
        return "Recv OK!"
    
    def send(self,info):
        return "Send OK!"

    def show(self):
        print(f"Show: {self.content}")

# 创建InfoServer的代理类。这里需要注意，代理模式在使用过程中，应尽量对抽象类进行代理，而尽量不要直接对加过修饰和方法的子类进行代理。
# 代理类和被代理类之间要尽可能减少耦合，服从单一职责原则。
class ProxyServer:
    def __init__(self,server):
        self.server = server

# InfoServer的代理类,用于授权
class WhiteInfoServerProxy(ProxyServer):
    def __init__(self,server):
        super().__init__(server)
        self.white_list = []

    def recv(self,info):
        addr = info.get("address",0)
        if not addr in self.white_list:
            return "Address not in white list"
        else:
            return self.server.recv(info)
    def send(self,info):
        addr = info.get("address",0)
        if not addr in self.white_list:
            return "Address not in white list"
        else:
            return self.server.send(info)
    def show(self):
        addr = info.get("address",0)
        if not addr in self.white_list:
            return "Address not in white list"
        else:
            self.server.show()

    def addWhite(self,addr):
        self.white_list.append(addr)
    def rmWhite(self,addr):
        self.white_list.remove(addr)    
    def clearWhite(self):
        self.white_list.clear()

#



# 场景2 资源消耗大的对象，通过代理提高性能
import time
class SalesManager:
    def __init__(self):
        self.busy = 'No'

    def work(self):
        self.busy = 'Yes'
        print("Sales Manager working...")
        time.sleep(2)
        # self.busy = 'No'

    def talk(self):
        if self.busy == 'No':
            print("Sales Manager ready to talk")

class Proxy:
    def __init__(self,sale):
        self.sale = sale

    def work(self):
        print("Proxy checking for Sales Manager availability")
        if self.sale.busy == 'No':
            self.sale.talk()
            self.sale.work()
        else:
            print("Sales Manager is busy")


if __name__ == '__main__':
    # 场景1
    # server= InfoServer()
    # proxy_server = WhiteInfoServerProxy(server)
    # proxy_server.addWhite("1")
    # re1 = proxy_server.recv({"address":"1","content":"Hello"})
    # proxy_server.rmWhite("1")
    # re2 = proxy_server.send({"address":"1","content":"Hello"})
    # print(re1)
    # print(re2)
    # del proxy_server
    # server.show()
    # 场景2
    sale = SalesManager()
    proxy_sale = Proxy(sale)
    proxy_sale.work()
    proxy_sale.work()

